/*
 * @desc:
 * @Author: 钟强
 * @Date: 2021-11-30 16:43:04
 * @LastEditors: 钟强
 * @LastEditTime: 2021-12-22 18:07:49
 */
import router from './router'
import store from './store'

// 白名单
const whiteList = ['/login']

// 路由前置守卫

router.beforeEach(async (to, from, next) => {
  // 存在token，进入主页面

  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      // 判断用户信息是否获取
      // 如果不存在用户信息，则需要获取用户信息
      if (!store.getters.hasUserInfo) {
        // 触发获取用户信息的action,获取用户信息
        const { permission } = await store.dispatch('user/getUserInfo')
        const filterRoutes = await store.dispatch(
          'permission/filterRoutes',
          permission.menus
        )

        // 利用addRouter 动态添加路由
        filterRoutes.forEach(item => {
          router.addRoute(item)
        })
        return next(to.path)
      }

      next()
    }
  } else {
    if (whiteList.indexOf(to.path) > -1) {
      next()
    } else {
      next('/login')
    }
  }
})
